package sg.edu.nus.iss.umpire.dao.jpa;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import sg.edu.nus.iss.umpire.dao.BaseDao;
import sg.edu.nus.iss.umpire.support.NonThreadSafe;

@NonThreadSafe
public class BaseDaoImpl<K, T> implements BaseDao<T> {
	protected EntityManager em;
	protected Class<T> entityClass;

	@SuppressWarnings("unchecked")
	protected BaseDaoImpl(EntityManager em) {
		this.em = em;
		entityClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[1];
	}

	@Override
	public void insert(T obj) {
		em.persist(obj);
	}

	@Override
	public void update(T obj) {
		em.merge(obj);
	}



	@Override
	public T getByKey(Serializable key) {
		return em.find(entityClass, key);
	}

	@Override
	public void deleteByKey(Serializable key) {
		T obj = em.find(entityClass, key);
		em.remove(obj);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> loadAll() {
		String query = "SELECT FROM " + entityClass.getName() + " entity";
		Query q = em.createQuery(query);
		q.setHint("datanucleus.appengine.datastoreReadConsistency", "EVENTUAL");
		return (List<T>) q.getResultList();
	}

}
